package com.bizark.rpc.log.service.impl;

import com.bizark.rpc.common.dao.DaoClient;
import com.bizark.rpc.common.tool.SysToolHelper;
import com.bizark.rpc.log.service.SysLogService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class SysLogServiceImpl implements SysLogService {

    private DaoClient daoClient;

    @Autowired(required = false)
    public void setDaoClient(DaoClient daoClient) {
        this.daoClient = daoClient;
    }


    private Logger logger = LoggerFactory.getLogger(SysLogServiceImpl.class);

    @Override
    public void error(Exception e) {

    }

    @Override
    public void error(String errorItem, String errorInfo) {
        error(errorItem, errorInfo, "", "", "");
    }

    @Override
    public void error(String errorItem, Exception e) {
        error(errorItem, e, "", "");
    }

    @Override
    public void error(String item, String content, String username, String ip, String userid) {
        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(item)) {
            return;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("logid", SysToolHelper.getUuid());
        map.put("item", item);
        map.put("error", content);
        map.put("ip", ip == null ? "" : ip);
        map.put("username", username == null ? "" : username);
        map.put("userid", userid == null ? "" : userid);
        String sql = "com.dessert.sys_error_log.addLog";
        try {
            daoClient.update(sql, map);
        } catch (RuntimeException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        logger.error(item + ":" + content);
    }

    @Override
    public void error(String errorItem, Exception e, String userId, String userIp) {

    }

    @Override
    public void addOperatingLog(Map<String, Object> logMap) {

    }


    /**
     * 〈获取异常描述〉
     *
     * @param e
     * @return
     * @see [相关类/方法]（可选）
     * @since [产品/模块版本] （可选）
     */
    private String getExceptionDesc(Exception e) {
        StringBuilder builder = new StringBuilder();
        if (e != null && e.getStackTrace() != null && e.getStackTrace().length > 0) {
            builder.append("from:").append(e.getStackTrace()[0].toString())
                    .append("<br/>");
        }
        builder.append("error:").append(String.valueOf(e));
        return builder.toString();
    }



}
